import React, { Component } from 'react';
import { connect } from 'dva';
import { Link, routerRedux } from 'dva/router';
import MyScroll from '../../components/MyScroll/MyScroll';
import {  Icon ,Button,Flex,List,Modal,DatePicker,Picker,ActionSheet,Toast,ImagePicker} from 'antd-mobile';
import { accountManagementC } from "./accountManagement.less";
import NavTopBar from '../../components/NavTopBar/NavTopBar';
import NoLazyImg from '../../components/NoLazyImg/NoLazyImg';
import { createForm } from 'rc-form';
import moment from 'moment';
import noHeadsvg from "../../assets/img/noHead.svg";

const Item = List.Item;
const sex = ["保密","女","男"];
const nowTimeStamp = Date.now();
const now = new Date(nowTimeStamp);
// GMT is not currently observed in the UK. So use UTC now.
const utcNow = new Date(now.getTime() + (now.getTimezoneOffset() * 60000));


class AccountManagement extends Component {
    constructor(props) {
        super(props);
        this.state = {
            sexVisible: false,
            dateVisible:false,
            sex:"",
            date: "",
            time: now,
            utcDate: utcNow,
            dpValue: null,
            customChildValue: null,
            visible: false,
            files: [],
        };
    }

    changeIcon = () => {
        this.showActionSheet();
    }

    imgChange = (files, type, index) => {
        this.setState({
            files,
        });
        this.props.dispatch({type:"orderList/upLoadEFF",obj:{upfile: files[files.length - 1].file}}).then(res => this.imgURL = res.ret.url);

    }

    showActionSheet = () => {
        const BUTTONS = [(<label style={{display: "block", height: "100%", width: "100%"}} htmlFor="inputFile">上传头像</label>), '取消'];
        ActionSheet.showActionSheetWithOptions({
            options: BUTTONS,
            cancelButtonIndex: BUTTONS.length - 1,
            maskClosable: true,
        }, (buttonIndex) => {
            if (buttonIndex == 0) {
                this.refs.head.click();
                this.refs.imgClick.onImageClick(1);
            }
        });
    }
    changeFile = (e) => {
        const files = this.refs.head.files[0];
        console.log(files);
        this.props.dispatch({type:"accountManagement/upLoadEFF",obj:{upfile:files}}).then((result)=>{
            console.log(result, "result");
            if (result.code == 200) {
                const imgUrl = result.ret.url;
                this.props.dispatch({type:"accountManagement/editMemberEFF",obj:{imgUrl: imgUrl}}).then((r)=>{
                    console.log(r, "r");
                    if(r.code==200){
                        Toast.success(r.msg, 1.5, ()=>{
                            this.props.dispatch({type:"accountManagement/DetaillEFF"});
                        });
                    } else {
                        Toast.fail(r.msg, 1.5);
                    }
                })
            }
        })
    }
    showSexSheet = () => {
        const BUTTONS = ['保密', '男','女',  '取消'];
        ActionSheet.showActionSheetWithOptions({
                options: BUTTONS,
                cancelButtonIndex: BUTTONS.length - 1,
                maskClosable: true,
            },
            (buttonIndex) => {
                if (buttonIndex == 3) {
                    return;
                }
                this.props.dispatch({type:"accountManagement/editMemberEFF",obj:{sex:buttonIndex}}).then((r)=>{
                    if(r.code==200){
                        Toast.success(r.msg, 1.5, ()=>{
                            this.props.dispatch({type:"accountManagement/DetaillEFF"});
                        });
                    } else {
                        Toast.fail(r.msg, 1.5);
                    }
                })
            });
    }


    onChangeBirthday = (date) => {
        const dateStr = date.format('YYYY-MM-DD');
        this.props.dispatch({type:"accountManagement/editMemberEFF",obj:{birthday:dateStr}}).then((r)=>{
            if(r.code==200){
                Toast.success(r.msg, 1.5, ()=>{
                    this.props.dispatch({type:"accountManagement/DetaillEFF"});
                });
            } else {
                Toast.fail(r.msg, 1.5);
            }
        })
    }

    // componentDidMount() {
    //     this.refs.head.click();
    // }

    render() {
        const { accountManagement = {} } = this.props;
        const {avatar="", } = accountManagement;
        const { getFieldProps } = this.props.form;
        const memberBirthday = accountManagement.birthday&&moment(accountManagement.birthday).utcOffset(8);
        const maxDate = moment().utcOffset(8);
        const minDate = moment('1900-01-01 +0800', 'YYYY-MM-DD Z').utcOffset(8);
        function siblings(elm) {
            var a = [];
            var p = elm.parentNode.children;
            for(var i =0,pl= p.length;i<pl;i++) {
                if(p[i] !== elm) a.push(p[i]);
            }
            return a;
        }

        console.log(this, "asdasd");
        return (
            <Flex style={{
                height:"100%"
            }} direction="column"

            >
                <NavTopBar isBlack={true} title="账户管理" dispatch={this.props.dispatch} jumpUrl={`/my`}/>
                <MyScroll className={ accountManagementC }>
                    <List className="headerImg" style={{margin:".2rem 0"}}>
                        <ImagePicker
                            ref="imgClick"
                            style={{position: "absolute", opacity: "0"}}
                            files={this.state.files}
                            onChange={this.imgChange}
                            selectable={this.state.files.length < 1}
                        />
                        <Item extra={accountManagement.avatar==""?<Icon type={noHeadsvg.id} style={{height:"1.2rem",width:"1.2rem"}}/>: <NoLazyImg  src={avatar} alt="" style={{height:".8rem",width:".8rem",borderRadius:"100%"}}/>} onClick={this.changeIcon}>头像</Item>
                    </List>
                    <List style={{marginBottom:".2rem"}}>
                        <Item  extra={accountManagement.name}>用户名</Item>
                        <Item extra={accountManagement.truename==''?accountManagement.name:accountManagement.truename} arrow="horizontal" onClick={()=>{
                            this.props.dispatch(routerRedux.push({
                                pathname: `/makeName/${accountManagement.truename==''?accountManagement.name:accountManagement.truename}`,
                            }));
                        }}>昵称</Item>
                        <Item extra={accountManagement.sex==1?"男":accountManagement.sex==2?"女":accountManagement.sex==0?"保密":""} arrow="horizontal" onClick={this.showSexSheet}>性别</Item>
                        <DatePicker
                            mode="date"
                            title="选择生日"
                            extra="Optional"
                            minDate= { new Date("July 21, 1900 01:15:00") }
                            value={accountManagement.birthday ? new Date(accountManagement.birthday) : new Date()}
                            onChange={date => {
                                this.props.dispatch({type:"accountManagement/editMemberEFF",obj:{birthday: date}}).then((r)=>{
                                    if(r.code==200){
                                        Toast.success(r.msg, 1.5, ()=>{
                                            this.props.dispatch({type:"accountManagement/DetaillEFF"});
                                        });
                                    } else {
                                        Toast.fail(r.msg, 1.5);
                                    }
                                })
                            }}
                        >
                        <Item  arrow="horizontal" >出生日期</Item>
                        </DatePicker>
                    </List>
                    <List>
                        <Item  arrow="horizontal" onClick={()=>{
                            this.props.dispatch(routerRedux.push({
                                pathname: `/orderAddress`,
                            }));
                        }}>地址管理</Item>
                        <Item extra="可修改密码" arrow="horizontal" onClick={()=>{
                            this.props.dispatch(routerRedux.push({
                                pathname:`/security/${accountManagement.mobile}`
                            }));
                        }}>账号安全</Item>
                        <Item  arrow="horizontal" onClick={()=>{
                            let arr=[accountManagement.availablePredeposit,accountManagement.freezePredeposit]
                            this.props.dispatch(routerRedux.push({
                                pathname: `/balance/${arr}`,
                            }));
                        }}>余额充值</Item>
                        <Item  arrow="horizontal" onClick={()=>{
                            this.props.dispatch(routerRedux.push({
                                pathname:`/thirdParty`
                            }))
                        }}>关联账号</Item>
                        <Item  arrow="horizontal"onClick={()=>{
                            this.props.dispatch(routerRedux.push({
                                pathname:`/myFeedback`
                            }))
                        }}>意见反馈</Item>
                        <Item  arrow="horizontal" style={{marginBottom:"1.3rem"}}onClick={()=>{
                            this.props.dispatch(routerRedux.push({
                                pathname:`/aboutLM`
                            }))
                        }}>关于名食汇</Item>
                    </List>
                </MyScroll>
                    <Button style={{width:"100%",backgroundColor:"#ff0036",color:"#fff",position:"fixed",bottom:"0"}} onClick={()=>{
                        localStorage.removeItem('token');
                        sessionStorage.removeItem('token');
                        this.props.dispatch({type:'accountManagement/loginOutEFF'}).then((r)=>{
                            if(r.code==200){
                                Toast.success(r.msg, 1.5, ()=>{
                                    localStorage.removeItem('token');
                                    sessionStorage.removeItem('token');
                                    // 清空数据。。。
                                    this.props.dispatch({type: 'my/clearState'});

                                    this.props.dispatch(routerRedux.replace({
                                        pathname: '/login',
                                    }))
                                });
                            } else {
                                Toast.fail(r.msg, 1.5);
                            }
                        })
                    }}>退出当前账号</Button>
                <input type="file" ref="head" id="inputFile" name="image" style={{display: 'none', marginBottom: "2rem"}} accept="image/*"
                        onChange={(e) => this.changeFile(e)}/>
            </Flex>
        );
    }
}


export default connect(({ accountManagement, my }) => ({ accountManagement, my }))(createForm()(AccountManagement));
